package cn.iocoder.yudao.module.comment.service.comment1;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.comment.controller.admin.comment1.vo.*;
import cn.iocoder.yudao.module.comment.dal.dataobject.comment1.CommentDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.comment.dal.mysql.comment1.CommentMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.comment.enums.ErrorCodeConstants.*;

/**
 * 旅游线路评论 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CommentServiceImpl implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Override
    public Long createComment(CommentSaveReqVO createReqVO) {
        // 插入
        CommentDO comment = BeanUtils.toBean(createReqVO, CommentDO.class);
        if (comment.getContent() != null) {
            String content = comment.getContent();
            content = content.replaceAll("(?i)<p[^>]*>", "");
            content = content.replaceAll("(?i)</p>", "");
            comment.setContent(content);
        }
        commentMapper.insert(comment);
        // 返回
        return comment.getCommentId();
    }

    @Override
    public void updateComment(CommentSaveReqVO updateReqVO) {
        // 校验存在
        validateCommentExists(updateReqVO.getCommentId());
        CommentDO updateObj = BeanUtils.toBean(updateReqVO, CommentDO.class);
        if (updateObj.getContent() != null) {
            String content = updateObj.getContent();
            content = content.replaceAll("(?i)<p[^>]*>", "");
            content = content.replaceAll("(?i)</p>", "");
            updateObj.setContent(content);
        }
        commentMapper.updateById(updateObj);
    }

    @Override
    public void deleteComment(Long id) {
        // 校验存在
        validateCommentExists(id);
        // 删除
        commentMapper.deleteById(id);
    }

    private void validateCommentExists(Long id) {
        if (commentMapper.selectById(id) == null) {
            throw exception(COMMENT_NOT_EXISTS);
        }
    }

    @Override
    public CommentDO getComment(Long id) {
        return commentMapper.selectById(id);
    }

    @Override
    public PageResult<CommentDO> getCommentPage(CommentPageReqVO pageReqVO) {
        return commentMapper.selectPage(pageReqVO);
    }

}